package com.excel.poi.utils;

import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.lang.reflect.Field;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Miaoxiong Fan
 * @description 公共类型转换工具
 * @date 2019/1/22
 * @return
 */
public class Converters {

    /**
     * @author Miaoxiong Fan
     * @description bean之间进行类型转换
     * @date 2019/1/22
     * @Param source 待转换bean
     * @Param target 指定转换输出对象class
     * @return
     */
    public static <S, T> T to(S source, Class<T> target) {
        if (source == null) return null;
        try {
            T t = target.newInstance();
            BeanUtils.copyProperties(source, t);
            return t;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @author Miaoxiong Fan
     * @description List之间进行类型转换
     * @date 2019/1/22
     * @Param source 待转换List
     * @Param target 指定转换输出对象class
     * @return
     */
    public static <S, T> List<T> to(List<S> source, Class<T> target) {
        if (CollectionUtils.isEmpty(source)) return Collections.emptyList();
        try {
            return source.stream().map(e -> to(e, target)).collect(Collectors.toList());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * @author Miaoxiong Fan
     * @description Set之间进行类型转换
     * @date 2019/1/22
     * @Param source 待转换Set
     * @Param target 指定转换输出对象class
     * @return
     */
    public static <S, T> Set<T> to(Set<S> source, Class<T> target) {
        if (CollectionUtils.isEmpty(source)) return Collections.emptySet();
        try {
            return source.stream().map(e -> to(e, target)).collect(Collectors.toSet());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static<S> Map to(S source) throws IllegalAccessException {
        Map<String,String> map = new HashMap<>();
        Field[] fields = source.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            map.put(field.getName() , (String) field.get(source));
        }
        return map;
    }

    public static<S> List<Map<String,String>> to(List<S> list) throws IllegalAccessException {
        List<Map<String,String>> result = new ArrayList<>();
        for (S s : list) {
            result.add(to(s));
        }
        return result;
    }
}
